package com.digitalchina.lxnsy.activity.old;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.FarmingRecordVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.entity.PesticideFertilizerVO;
import com.digitalchina.lxnsy.entity.PesticideV2VO;
import com.digitalchina.lxnsy.entity.PlanProductVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.SharedPreferencesUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/8/27 15:45
 * 修改备注：
 * ================================================
 */
public class AddFarmingRecordActivity extends BaseActivity {

    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.tv_weather)
    TextView tvWeather;
    @Bind(R.id.tv_phenological)
    TextView tvPhenological;
    @Bind(R.id.layout_crop_manage)
    LinearLayout layoutCropManage;
    @Bind(R.id.et_fertilizer)
    EditText etFertilizer;
    @Bind(R.id.et_water)
    EditText etWater;
    @Bind(R.id.et_area)
    EditText etArea;
    @Bind(R.id.layout_fertilizer)
    LinearLayout layoutFertilizer;
    @Bind(R.id.et_msg_info)
    EditText etMsgInfo;
    @Bind(R.id.cb_crop)
    CheckBox cbCrop;
    @Bind(R.id.cb_fertilizer)
    CheckBox cbFertilizer;
    @Bind(R.id.flow_layout)
    TagFlowLayout flowLayout;
    @Bind(R.id.sdv_img0)
    SimpleDraweeView sdvImg0;
    @Bind(R.id.sdv_img1)
    SimpleDraweeView sdvImg1;
    @Bind(R.id.sdv_img2)
    SimpleDraweeView sdvImg2;
    @Bind(R.id.sdv_img3)
    SimpleDraweeView sdvImg3;
    @Bind(R.id.Layout_add_water)
    LinearLayout LayoutAddWater;
    @Bind(R.id.Layout_no_water)
    LinearLayout LayoutNoWater;


    private TagAdapter<PlanProductVO.FarmOperationBean> tagAdapter; // 单选适配器
    private List<PlanProductVO.FarmOperationBean> farmList = new ArrayList<>(); // 农事操作list

    private List<PesticideV2VO> pesticideList = new ArrayList<>(); // 农药化肥总list


    //typeCode --------->>  300201  农药
    //typeCode --------->>  300202  化肥

    private List<PesticideV2VO> nyList = new ArrayList<>(); // 农药list
    private List<PesticideV2VO> hfList = new ArrayList<>(); // 化肥list


    /**
     * 农事记录保存编辑接口
     *
     * @param productionId            生产计划Id
     * @param userAccId               用户Id
     * @param cropType                0作物管理 1用肥用药
     * @param operationDate           操作日期
     * @param weather                 天气
     * @param weatherDescribe         天气描述
     * @param phId                    物后期Id
     * @param phaseName               物后期name
     * @param farmingOperations       农事操作Id 当cropType为0时必传
     * @param farmingOperationsimgs   图片多个以，隔开
     * @param specification           补充说明
     * @param perMuTotal              亩数总量
     * @param waterTotal              兑水总量
     * @param pesticideFertilizerList 农事记录管理农药、肥料Json字符串
     * @param id                      农事记录Id
     */

    private String productionId = "";
    private String cropType = "0";
    private String operationDate = "";
    private String weather = "";
    private String weatherDescribe = "";
    private String phId = "";
    private String phaseName = "";
    private String farmingOperations = "";
    private String farmingOperationsimgs = "";
    private String specification = "";
    private String perMuTotal = "";
    private String waterTotal = "";
    private String pesticideFertilizerList = "";
    private String id = "";

    // 时间选择器
//    private TimePickerView pvTime;
    private OptionsPickerView pvWeather, pvPhase, pvNy, pvHf;

    private List<String> listT = new ArrayList<>();
    private List<List<String>> listW = new ArrayList<>();

    private PlanProductVO planProductVO;
    // 物候期
    private List<PlanProductVO.ProductStandardBean.PhaseMsgInfosBean> whList = new ArrayList<>();
    // 新增药剂/肥料list
    private List<PesticideFertilizerVO> fertilizerList = new ArrayList<>();
    // 农事记录ID 修改时用
    private String agriculturalRecordsId = "";


    // 图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    private ImagePicker imagePicker;
    private String[] imgs = {"", "", "", ""};
    private SimpleDraweeView[] sdvArray = new SimpleDraweeView[4];

    private int select = 0;

    private String inTime = "";// 进入时间
    private String faroutTime = "";//农事保存退出时间
    private String outTime = "";//   离开时间(通用)

    private FarmingRecordVO recordVO;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (StringUtil.isStrEmpty(faroutTime)) {
            outTime = DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD_EN_HH_MM_SS_EN);
            BusinessPlan.saveStayOftenInfo(this, productionId, "0", inTime, faroutTime, outTime, mHandler);
        }
    }

    @Override
    public void setLayout() {
        inTime = DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD_EN_HH_MM_SS_EN);
        setContentLayout(R.layout.activity_add_farming_record);
        setTitle("新增农事记录");
    }

    @Override
    public void initMember() {

        String w = SharedPreferencesUtil.getValue(this, UserXML.XML_NAME_USER, "curWeather", "");

        if(!StringUtil.isStrEmpty(w)){
            tvWeather.setText(w);
            String s[] = w.split(" ");
            weather = s[0];
            weatherDescribe = s[1];
        }

        sdvArray[0] = sdvImg0;
        sdvArray[1] = sdvImg1;
        sdvArray[2] = sdvImg2;
        sdvArray[3] = sdvImg3;

        if (getIntent().hasExtra("FarmingRecordVO")) {
            recordVO = (FarmingRecordVO) getIntent().getSerializableExtra("FarmingRecordVO");
            productionId = recordVO.getProductionId();
            setView();
        } else
            productionId = getIntent().getStringExtra("productionId");

        // 获取物候期
        BusinessPlan.productionShow(this, productionId, mHandler);
        // 获取农药
        BusinessPlan.getPesticideData(this, mHandler);

        initOptPicker();

    }

    //如果是修改则加载带入数据
    private void setView() {
        //公共部分
        id = recordVO.getId();
        cropType = recordVO.getCropType();
        operationDate = recordVO.getOperationDate();
        tvTime.setText(operationDate);
        weather = recordVO.getWeather();
        weatherDescribe = recordVO.getWeatherDescribe();
        tvWeather.setText(weather + " " + weatherDescribe);
        phId = recordVO.getPhId();
        phaseName = recordVO.getPhaseNameShow();
        tvPhenological.setText(phaseName);
        // 图片
        if (recordVO.getFarmingOperationsimgs() != null && recordVO.getFarmingOperationsimgs().size() > 0) {
            for (int i = 0; i < recordVO.getFarmingOperationsimgs().size(); i++) {
                imgs[i] = recordVO.getFarmingOperationsimgs().get(i).getImage();
                FrescoUtil.showImageSmall(imgs[i], sdvArray[i]);
            }
        }
        // 说明
        specification = recordVO.getSpecification();
        etMsgInfo.setText(specification);

        if (cropType.equals("0")) {//作物管理
            cbCrop.setChecked(true);
            cbFertilizer.setChecked(false);
            layoutCropManage.setVisibility(View.VISIBLE);
            layoutFertilizer.setVisibility(View.GONE);
//            farmingOperations = recordVO.getFarmingOperations().getId();
        } else { // 用肥用药
            cbCrop.setChecked(false);
            cbFertilizer.setChecked(true);
            layoutCropManage.setVisibility(View.GONE);
            layoutFertilizer.setVisibility(View.VISIBLE);

            if (!StringUtil.isStrEmpty(recordVO.getWaterTotal())) {
                etWater.setText(recordVO.getWaterTotal());
            }
            if (!StringUtil.isStrEmpty(recordVO.getWaterTotal())) {
                etArea.setText(recordVO.getPerMuTotal());
            }

            if (recordVO.getIspesticideFertilizers() != null && recordVO.getIspesticideFertilizers().size() > 0) {
                for (int i = 0; i < recordVO.getIspesticideFertilizers().size(); i++) {
                    LayoutAddWater.addView(newView(recordVO.getIspesticideFertilizers().get(i)));
                }
            }

            if (recordVO.getNotpesticideFertilizers() != null && recordVO.getNotpesticideFertilizers().size() > 0) {
                for (int i = 0; i < recordVO.getNotpesticideFertilizers().size(); i++) {
                    LayoutNoWater.addView(newView(recordVO.getNotpesticideFertilizers().get(i)));
                }
            }
        }
    }

    @Override
    public void addListener() {
        flowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                farmingOperations = farmList.get(position).getId();
                return false;
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (isFinishing())
                    return;

                switch (msg.what) {
                    case MSG.MSG_PRODUCTION_SHOW_SUCCESS:// 获取物候期
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_PRODUCTION_SHOW_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_FARMING_SAVE_SUCCESS: // 提交表单
                        showToast("保存成功");
                        faroutTime = DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD_EN_HH_MM_SS_EN);
                        BusinessPlan.saveStayOftenInfo(AddFarmingRecordActivity.this, productionId, "0", inTime, faroutTime, outTime, mHandler);
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_FARMING_SAVE_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_FILE_UPLOAD_SUCCESS: // 上传图片
                        dismissDialog();
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "fileStorage", FileVO.class);
                        if (fileVO != null) {
                            imgs[select] = fileVO.getName();
                            setImageView(fileVO.getName());
                        }
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString() + "");
                        break;
                    case MSG.MSG_GET_PESTICIDE_DATA_SUCCESS: // 获取农药化肥分类
                        pesticideList = FastJsonUtil.getListBean(msg.obj.toString(), PesticideV2VO.class);

                        if (pesticideList != null) {
                            for (int i = 0; i < pesticideList.size(); i++) {
                                if ("300201".equals(pesticideList.get(i).getType()))
                                    nyList.add(pesticideList.get(i));
                                else
                                    hfList.add(pesticideList.get(i));
                            }

                            pvHf.setPicker(hfList);

                            List<List<PesticideV2VO.PesticidesBean>> list = new ArrayList<>();
                            for (int i = 0; i < nyList.size(); i++) {
                                list.add(nyList.get(i).getPesticides());
                            }

                            pvNy.setPicker(nyList, list);
                        }


                        break;
                }
            }
        };
    }

    private void setImageView(String fileName) {
        FrescoUtil.showImageSmall(fileName, sdvArray[select]);
    }

    @Override
    public void callBack(Object object) {

        planProductVO = FastJsonUtil.getBean(object.toString(), "productPlan", PlanProductVO.class);

        if (planProductVO != null && planProductVO.getProductStandard() != null) {

            whList = planProductVO.getProductStandard().getPhaseMsgInfos();

            phId = planProductVO.getPhaseMsgInfo().getId();
            phaseName = planProductVO.getPhaseMsgInfo().getPhaseName();
            tvPhenological.setText(planProductVO.getPhaseMsgInfo().getPhaseName() + "");

            pvPhase.setPicker(whList);

            farmList = planProductVO.getPhaseMsgInfo().getFarmOperation();
            tagAdapter.setData(farmList);


//            // 当为作物管理时 遍历
//            if (recordVO != null && recordVO.getFarmingOperations() != null && cropType.equals("0"))
//                if (farmList != null && farmList.size() > 0)
//                    for (int i = 0; i < farmList.size(); i++) {
//                        if (farmList.get(i).getId().equals(recordVO.getFarmingOperations().getId())) {
//                            tagAdapter.setSelectedList(i);
//                            break;
//                        }
//                    }

        }


    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.cb_crop, R.id.cb_fertilizer, R.id.layout_time, R.id.layout_weather, R.id.layout_phenological, R.id.layout_select_fertilizer, R.id.sdv_img1, R.id.sdv_img2, R.id.sdv_img3, R.id.sdv_img0,
            R.id.bt_save, R.id.tv_add_fertilizer})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_save:

                getFertilizerList();

                if (StringUtil.isStrEmpty(operationDate)) {
                    showToast("请选择操作日期");
                    return;
                }

                if (StringUtil.isStrEmpty(weather)) {
                    showToast("请选择天气");
                    return;
                }

                if (StringUtil.isStrEmpty(phId)) {
                    showToast("请选择物候期");
                    return;
                }

                if (cropType.equals("0")) {
                    if (StringUtil.isStrEmpty(farmingOperations)) {
                        showToast("请选择农事操作");
                        return;
                    }
                } else {
                    if (StringUtil.isStrEmpty(pesticideFertilizerList)) {
                        showToast("请选择农药/化肥");
                        return;
                    }

                    perMuTotal = etArea.getText().toString();
                    if (LayoutNoWater.getChildCount() > 0 && StringUtil.isStrEmpty(perMuTotal)) {
                        showToast("请填写亩数总量");
                        return;
                    }

                    waterTotal = etWater.getText().toString();
                    if (LayoutAddWater.getChildCount() > 0 && StringUtil.isStrEmpty(waterTotal)) {
                        showToast("请填写兑水总量");
                        return;
                    }
                }


                farmingOperationsimgs = getImages();
                specification = etMsgInfo.getText().toString();

                BusinessPlan.farmingSave(AddFarmingRecordActivity.this, productionId, cropType, operationDate, weather, weatherDescribe, phId, phaseName, farmingOperations,
                        farmingOperationsimgs, specification, perMuTotal, waterTotal, pesticideFertilizerList, id, mHandler);

                break;
            case R.id.cb_crop:
                setCheckBox(0);
                break;
            case R.id.cb_fertilizer:
                setCheckBox(1);
                break;
            case R.id.layout_time:
                showDatePicker();
                break;
            case R.id.layout_weather:
                pvWeather.show();
                break;
            case R.id.layout_phenological:
                pvPhase.show();
                break;
            case R.id.sdv_img0:
                selectImage(0);
                break;
            case R.id.sdv_img1:
                selectImage(1);
                break;
            case R.id.sdv_img2:
                selectImage(2);
                break;
            case R.id.sdv_img3:
                selectImage(3);
                break;
            case R.id.layout_select_fertilizer:

                new MaterialDialog.Builder(AddFarmingRecordActivity.this)
                        .title("请选择类型")
                        .items(R.array.isAddWater)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                if (position == 0)
                                    pvNy.show();
                                else
                                    pvHf.show();
                            }
                        })
                        .show();

                break;

            case R.id.tv_add_fertilizer: // 自定义添加

                if (StringUtil.isEditEmpty(etFertilizer)) {
                    showToast("请填写药剂/化肥");
                    return;
                }

                new MaterialDialog.Builder(AddFarmingRecordActivity.this)
                        .title("您添加的“" + etFertilizer.getText().toString() + "”是农药还是肥料？")
                        .items(R.array.isAddWater)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                                if (position == 0) // 不需要兑水
                                    LayoutNoWater.addView(newView(0, etFertilizer.getText().toString(), ""));
                                else
                                    LayoutAddWater.addView(newView(1, etFertilizer.getText().toString(), ""));

                                etFertilizer.setText("");
                            }
                        })
                        .show();

                break;
        }
    }

    /**
     * 显示日期选择
     */
    private void showDatePicker() {

        Calendar calendar = Calendar.getInstance();
        int mYear = calendar.get(Calendar.YEAR);
        int mMonth = calendar.get(Calendar.MONTH);
        int mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                operationDate = year + "-" + (month + 1) + "-" + dayOfMonth;
                tvTime.setText(operationDate);
            }
        }, mYear, mMonth, mDayOfMonth);

        datePickerDialog.show();
    }


    // 动态新增view 修改用 渲染数据
    private View newView(FarmingRecordVO.IspesticideFertilizersBean vo) {
        final View view = View.inflate(this, R.layout.item_add_farm_2h, null);
        ImageView ivDelete = view.findViewById(R.id.iv_delete);
        TextView tvName = view.findViewById(R.id.tv_name);
        TextView tvCode = view.findViewById(R.id.tv_code);
        EditText etUse = view.findViewById(R.id.et_use);
        EditText etXishi = view.findViewById(R.id.et_xishi);
        Switch swUnit = view.findViewById(R.id.sw_unit);

        tvName.setText(vo.getName());
        tvCode.setText(vo.getCode());
        etUse.setText(vo.getConsumption());
        etXishi.setText(vo.getMultiple());
        swUnit.setChecked(vo.getUnit().equals("ml"));

        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutAddWater.removeView(view);
            }
        });
        return view;
    }

    private View newView(FarmingRecordVO.NotpesticideFertilizersBean vo) {
        final View view = View.inflate(this, R.layout.item_no_water, null);
        ImageView ivDelete = view.findViewById(R.id.iv_delete);
        TextView tvName = view.findViewById(R.id.tv_name);
        TextView tvCode = view.findViewById(R.id.tv_code);
        EditText etUse = view.findViewById(R.id.et_use);

        tvName.setText(vo.getName());
        tvCode.setText(vo.getCode());
        etUse.setText(vo.getConsumption());

        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutNoWater.removeView(view);
            }
        });
        return view;
    }

    // 动态新增view
    private View newView(int i, String name, String code) {
        if (i == 0) {// 不需要兑水
            final View view = View.inflate(this, R.layout.item_no_water, null);
            ImageView ivDelete = view.findViewById(R.id.iv_delete);
            TextView tvName = view.findViewById(R.id.tv_name);
            TextView tvCode = view.findViewById(R.id.tv_code);
            EditText etUse = view.findViewById(R.id.et_use);

            tvName.setText(name);
            tvCode.setText(code);

            ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LayoutNoWater.removeView(view);
                }
            });
            return view;

        } else {
            final View view = View.inflate(this, R.layout.item_add_farm_2h, null);
            ImageView ivDelete = view.findViewById(R.id.iv_delete);
            TextView tvName = view.findViewById(R.id.tv_name);
            TextView tvCode = view.findViewById(R.id.tv_code);
            EditText etUse = view.findViewById(R.id.et_use);
            EditText etXishi = view.findViewById(R.id.et_xishi);
            Switch swUnit = view.findViewById(R.id.sw_unit);

            tvName.setText(name);
            tvCode.setText(code);

            ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LayoutAddWater.removeView(view);
                }
            });
            return view;
        }


    }

    //获取所有动态添加的Item，找到控件的id，获取数据
    private void getFertilizerList() {
        for (int i = 0; i < LayoutNoWater.getChildCount(); i++) {
            View view = LayoutNoWater.getChildAt(i);
            TextView tvName = view.findViewById(R.id.tv_name);
            TextView tvCode = view.findViewById(R.id.tv_code);
            EditText etUse = view.findViewById(R.id.et_use);

            PesticideFertilizerVO vo = new PesticideFertilizerVO();
            vo.setAgriculturalRecordsId(agriculturalRecordsId);
            vo.setIsWater(false);
            vo.setName(tvName.getText().toString());
            vo.setCode(tvCode.getText().toString());
            vo.setConsumption(etUse.getText().toString());

            fertilizerList.add(vo);
        }

        for (int i = 0; i < LayoutAddWater.getChildCount(); i++) {
            View view = LayoutAddWater.getChildAt(i);
            TextView tvName = view.findViewById(R.id.tv_name);
            TextView tvCode = view.findViewById(R.id.tv_code);
            EditText etUse = view.findViewById(R.id.et_use);
            EditText etXishi = view.findViewById(R.id.et_xishi);
            Switch swUnit = view.findViewById(R.id.sw_unit);

            PesticideFertilizerVO vo = new PesticideFertilizerVO();
            vo.setAgriculturalRecordsId(agriculturalRecordsId);
            vo.setIsWater(true);
            vo.setName(tvName.getText().toString());
            vo.setCode(tvCode.getText().toString());
            vo.setConsumption(etUse.getText().toString());
            vo.setMultiple(etXishi.getText().toString());
            if (swUnit.isChecked())
                vo.setUnit(swUnit.getTextOn().toString());
            else
                vo.setUnit(swUnit.getTextOff().toString());

            fertilizerList.add(vo);
        }

        if (fertilizerList != null && fertilizerList.size() > 0)
            pesticideFertilizerList = JSON.toJSONString(fertilizerList, true);
    }

    // 选择图片
    private void selectImage(int i) {
        select = i;
        if (StringUtil.isStrEmpty(imgs[select])) {
            Intent intent = new Intent(AddFarmingRecordActivity.this, ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT);
        } else {
            new MaterialDialog.Builder(AddFarmingRecordActivity.this)
                    .title("提示")
                    .content("是否删除这张照片？")
                    .positiveText("删除")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            imgs[select] = "";
                            Uri uri = Uri.parse("res://com.digitalchina.bigdata/" + R.drawable.selector_image_add);
                            sdvArray[select].setImageURI(uri);
                        }
                    })
                    .show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    showDialog("正在上传图片...");
                    BusinessFile.imageCompressAndUpload(this, images.get(0).path, mHandler);
                }

            }
        }
    }

    // 顶部选择
    private void setCheckBox(int i) {

        if (i == 0) {//作物管理
            cbCrop.setChecked(true);
            cbFertilizer.setChecked(false);
            layoutCropManage.setVisibility(View.VISIBLE);
            layoutFertilizer.setVisibility(View.GONE);
            cropType = "0";
        } else { // 用肥用药
            cbCrop.setChecked(false);
            cbFertilizer.setChecked(true);
            layoutCropManage.setVisibility(View.GONE);
            layoutFertilizer.setVisibility(View.VISIBLE);
            cropType = "1";
        }
    }

    private void initOptPicker() {

        //打开选择,本次允许选择的数量
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setMultiMode(false);    //是否多选模式




        listT.add("低于0℃");
        listT.add("0-5℃");
        listT.add("5-10℃");
        listT.add("10-15℃");
        listT.add("15-20℃");
        listT.add("20-25℃");
        listT.add("25-30℃");
        listT.add("30-35℃");
        listT.add("高于35℃");

        List<String> tempList = new ArrayList<>();
        tempList.add("晴");
        tempList.add("多云");
        tempList.add("阴");
        tempList.add("雨");
        tempList.add("雪");
        tempList.add("阵雨");
        tempList.add("雷阵雨");
        tempList.add("雨夹雪");
        tempList.add("小雨");
        tempList.add("中雨");
        tempList.add("大雨");
        tempList.add("暴雨");
        tempList.add("冻雨");
        tempList.add("阵雪");
        tempList.add("小雪");
        tempList.add("中雪");
        tempList.add("大雪");
        tempList.add("暴雪");
        tempList.add("浮尘");
        tempList.add("扬沙");
        tempList.add("沙尘暴");
        tempList.add("雾");
        tempList.add("浓雾");
        tempList.add("霾");

        for (int i = 0; i < listT.size(); i++) {
            listW.add(tempList);
        }


        // 天气
        pvWeather = new OptionsPickerView.Builder(AddFarmingRecordActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = listT.get(options1) + " " + listW.get(options1).get(option2);

                weather = listT.get(options1);
                weatherDescribe = listW.get(options1).get(option2);

                tvWeather.setText(select);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        pvWeather.setPicker(listT, listW);


        // 物候期
        pvPhase = new OptionsPickerView.Builder(AddFarmingRecordActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = whList.get(options1).getPhaseName();
                phId = whList.get(options1).getId();
                phaseName = whList.get(options1).getPhaseName();
                tvPhenological.setText(select);
                farmList = whList.get(options1).getFarmOperation();
                tagAdapter.setData(farmList);
            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();


        // 农药 双list
        pvNy = new OptionsPickerView.Builder(AddFarmingRecordActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = nyList.get(options1).getPesticides().get(option2).getName();
                if (nyList.get(options1).getIsWater() == 0)// 不需要兑水
                    LayoutNoWater.addView(newView(0, select, nyList.get(options1).getPesticides().get(option2).getCode()));
                else
                    LayoutAddWater.addView(newView(1, select, nyList.get(options1).getPesticides().get(option2).getCode()));

            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();


        // 化肥 单list
        pvHf = new OptionsPickerView.Builder(AddFarmingRecordActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                String select = hfList.get(options1).getName();
                newView(0, select, hfList.get(options1).getCode());
                if (hfList.get(options1).getIsWater() == 0)// 不需要兑水
                    LayoutNoWater.addView(newView(0, select, hfList.get(options1).getCode()));
                else
                    LayoutAddWater.addView(newView(1, select, hfList.get(options1).getCode()));

            }
        })
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();

        tagAdapter = new TagAdapter<PlanProductVO.FarmOperationBean>(farmList) {

            @Override
            public View getView(FlowLayout parent, int position, PlanProductVO.FarmOperationBean vo) {
                TextView tv = (TextView) mInflater.inflate(R.layout.view_text_view,
                        flowLayout, false);
                tv.setText(vo.getFarmName());
                return tv;
            }
        };

        flowLayout.setAdapter(tagAdapter);
    }

    public String getImages() {

        String s = "";
        for (String img : imgs) {
            if (!StringUtil.isStrEmpty(img))
                s += img + ",";
        }

        if (!StringUtil.isStrEmpty(s))
            s = s.substring(0, s.length() - 1);

        return s;
    }

}
